package com.mahao.util;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.HashMap;

import javax.imageio.ImageIO;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;

public class QRCodeByZXing {
	public static void createQRCode(String path,String imgName,String contents){
		int width = 300;
		int height = 300;
		String format="png";
		try {
			
			BitMatrix bm = new MultiFormatWriter().encode(new String(contents.getBytes("UTF-8"),"ISO-8859-1"), BarcodeFormat.QR_CODE, width, height);
			File file=new File(path);
			if(!file.exists()){
				file.mkdir();
			}
			file = new File(path+"\\"+imgName);
			if(!file.exists()){
				file.createNewFile();
			}
			Path pa = file.toPath();
			MatrixToImageWriter.writeToPath(bm, format, pa);
			System.out.println("二维码生成完毕");
		} catch (WriterException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static void anQRCode(String path){
		try {
			MultiFormatReader reader=new MultiFormatReader();
			File f=new File(path);
			if(f.exists()){
				BufferedImage image=ImageIO.read(f);
				BinaryBitmap bb=new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image)));
				HashMap map =new HashMap();
				map.put(EncodeHintType.CHARACTER_SET, "utf-8");
				Result result = reader.decode(bb,map);
				System.out.println("解析结果："+result.toString());
				System.out.println("二维码格式类型："+result.getBarcodeFormat());
				System.out.println("二维码文本内容："+result.getText());
			}else{
				System.out.println("文件不存在："+path);
			}
		} catch (NotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
